package com.denghq.projectbuilder.component.remote.config;

import com.denghq.projectbuilder.component.remote.client.UserClient;
import com.denghq.projectbuilder.component.remote.common.Constant;
import com.denghq.projectbuilder.component.remote.model.ResultInfoModel;
import com.denghq.projectbuilder.component.remote.model.UserRightViewModel;
import com.denghq.projectbuilder.component.remote.utils.UserContextHolder;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import feign.*;
import feign.codec.DecodeException;
import feign.codec.Decoder;
import feign.codec.Encoder;
import org.springframework.cloud.openfeign.support.SpringMvcContract;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;
import java.lang.reflect.Type;

@Configuration
public class WithOutGlobalTokenFeginClientConfiguration {

    /*    @Autowired
        private Decoder decoder;

        @Autowired
        private Encoder encoder;

        @Autowired
        private Client client;*/
    private static ObjectMapper MAPPER = new ObjectMapper();

    @Bean
    public UserClient userClient(Client client) {
        Decoder decoder = new Decoder() {

            @Override
            public Object decode(Response response, Type type) throws IOException, DecodeException, FeignException {
                if (response.status() == 404) {
                    return Util.emptyValueOf(type);
                } else if (response.body() == null) {
                    return null;
                } else return MAPPER.readValue(response.body().asInputStream(), new TypeReference<ResultInfoModel<UserRightViewModel>>() {
                });
            }
        };
        Encoder encoder = new Encoder.Default();
        //解决同名feignClient不能使用相同的自定义配置类问题
        UserClient userClient =
                Feign.builder().client(client)
                        .encoder(encoder)
                        .decoder(decoder)
                        .contract(new SpringMvcContract())
                        .requestInterceptor(requestTemplate -> {
                            String token = UserContextHolder.getAuthorization();
                            requestTemplate.header(com.denghq.projectbuilder.common.Constant.SERVICE_TOKEN_NAME, token);
                        })
                        .target(UserClient.class, "http://" + Constant.SERVICE_SMW_CODE);
        return userClient;
    }


}
